from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.http import Http404

import logging

from google.appengine.api import users

from memebase.models import Site

from memebase.utils import requires_logged_user
from memebase.views.sites import requires_existing_site

log = logging.getLogger('memebase.views.memes')
log.setLevel(logging.DEBUG)


def get_MemeCreateForm(user, site):
    from google.appengine.ext.db import djangoforms
    from memebase.models import Meme
    class MemeCreateForm(djangoforms.ModelForm):
        content = djangoforms.forms.CharField(label='Content', widget=djangoforms.forms.Textarea, required=True)
        class Meta:
            model = Meme
            fields = ['public_view', 'title']
        def save(self, commit=True):
            content = self.cleaned_data['content']
            public_view = self.cleaned_data['public_view']
            title = self.cleaned_data['title']
            meme = Meme.create(content=content, author=user, site=site, title=title, public_view=public_view)
            if not meme:
                self.errors['__all__'] = 'Error saving new Meme'
            return meme
    return MemeCreateForm

def meme_creation_permission_test(user, site, sitename):
    return site.can_create_meme(user)

@requires_existing_site
@requires_logged_user(google_admin=False, test=meme_creation_permission_test)
def create_meme(request, site, sitename):
    user = users.get_current_user()
    if request.method == 'GET':
        form_create = get_MemeCreateForm(user, site)()
        return render_to_response('memebase/create_meme.html', locals())
    elif request.method == 'POST':
        form_create = get_MemeCreateForm(user, site)(request.POST)
        if form_create.is_valid():
            meme = form_create.save()
            if meme:
                return HttpResponseRedirect(meme.get_absolute_url())
            else:
                log.warning('Unknown form error creating meme. Form: "%s"', form_create.cleaned_data)
        return render_to_response('memebase/create_meme.html', locals())

@requires_existing_site
def view_meme(request, site, sitename, memename):
    meme = site.get_meme_by_name(memename)
    if not meme: raise Http404
    user = users.get_current_user()   
    if meme.can_view(user):
        return render_to_response('memebase/view_meme.html', locals())
    else:
        from memebase.utils import access_denied_response
        return access_denied_response()

def get_conf(sitename, memename):
    conf = {
        'textarea_prefix': 'node_',
        'div_prefix': 'div_node_',
        'ajax_response': 'json',
        'ajax_mimetype': 'application/json',
        'ajax_method': 'get',
        'ajax_url': reverse('edit_meme_cmd',
            kwargs=dict(sitename=sitename, memename=memename)),
        'ajax_timeout': 60000, # ms
    }
    return conf

@requires_existing_site
def edit_meme(request, site, sitename, memename):
    meme = site.get_meme_by_name(memename)
    if not meme: raise Http404
    user = users.get_current_user()   
    if meme.can_edit(user):
        from django.utils import simplejson
        conf = get_conf(sitename, memename)
        conf_js = simplejson.dumps(conf)
        return render_to_response('memebase/edit_meme.html', locals())
    else:
        from memebase.utils import access_denied_response
        return access_denied_response()


@requires_existing_site
def edit_meme_save(request, site, sitename, memename):
    meme = site.get_meme_by_name(memename)
    if not meme: raise Http404
    user = users.get_current_user()   
    if meme.can_edit(user):
        if request.method == 'POST':
            conf = get_conf(sitename, memename)           
            textarea_prefix = conf['textarea_prefix']
            for field_name, [value] in request.POST.iteritems():
                if field_name.startswith(textarea_prefix):
                    node_name = field_name.replace(textarea_prefix, '')
                    node = meme.get_node_by_name(node_name)
                    if not node:
                        log.warning('%s tried to save non-existing node %s in meme %s', user, node_name, meme)
                    else:
                        node.save(content=value)
                else:
                    log.debug('%s posted a unknown field %s in meme %s', user, field_name, meme)
            return HttpResponseRedirect(meme.get_edit_url())
        else:
            raise Http404
    else:
        from memebase.utils import access_denied_response
        return access_denied_response()

@requires_existing_site
def edit_meme_cmd(request, site, sitename, memename):
    """Called via 'AJAX'"""
    meme = site.get_meme_by_name(memename)
    if not meme: raise Http404
    user = users.get_current_user()
    response = {'errors': [], 'nodes':[], 'tmpnode':{}}
    conf = get_conf(sitename, memename)       
    if meme.can_edit(user):
        textarea_prefix = conf['textarea_prefix']       
        command = request.GET.get('c')
        node_id = request.GET.get('id', '').replace(textarea_prefix, '')
        temp_id = request.GET.get('tempid', '')
        if command in ('ci', 'cs'):
            node = meme.get_node_by_name(node_id)
            if node:
                if command == 'ci':
                    # create a node in the same level as node
                    newnode = node.create_node()
                elif command == 'cs':
                    # create a node as subnode of node
                    newnode = node.create_subnode()
                else:
                    assert 0
                if newnode:
                    response['tmpnode']['newid'] = newnode.name()
                    response['tmpnode']['newfullpos'] = newnode.full_position()
                    response['tmpnode']['tempid'] = temp_id
                    for node, level in meme.transversal():
                        response['nodes'].append({
                            'id': node.name(),
                            'fullpos': node.full_position(),
                            })
                else:
                    message = 'Tried to create node in the same level as %s but failed' % node
                    log.warning(message)
                    response['errors'].append(message)
            else:
                response['errors'].append('Node with id %s not found' % node_id)
        else:
            response['errors'].append('Command %s not found' % command)

    else:
        response['errors'].append('Permission denied')
    from django.utils import simplejson
    return HttpResponse(simplejson.dumps(response), mimetype=conf['ajax_mimetype'])


@requires_existing_site
def list_memes(request, site, sitename):
    user = users.get_current_user()
    memes = site.get_all_visible_memes(user)
    user_can_create_meme = site.can_create_meme(user)
    if user_can_create_meme:
        form_create = get_MemeCreateForm(user, site)()
    return render_to_response('memebase/list_memes.html', locals())

